package com.schrodinger.config;

import com.schrodinger.service.HelloService;
import com.schrodinger.service.IHelloService;
import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.*;
import org.springframework.aop.aspectj.TypePatternClassFilter;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.support.DynamicMethodMatcher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

import java.lang.reflect.Method;

/**
 * Created by zhangli on 2017/9/22.
 */
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class HelloConfig {

    @Bean
    public IHelloService helloService(){
        return new HelloService();
    }

    @Bean
    public PointcutAdvisor advisor(){
        Pointcut pointcut = new Pointcut() {
            @Override
            public ClassFilter getClassFilter() {
                return new TypePatternClassFilter("com.schrodinger.service.*");
            }

            @Override
            public MethodMatcher getMethodMatcher() {
                return new DynamicMethodMatcher(){
                    @Override
                    public boolean matches(Method method, Class<?> targetClass, Object... args) {
                        return true;
                    }
                };
            }
        };
        Advice advice = new MethodInterceptor() {
            @Override
            public Object invoke(MethodInvocation invocation) throws Throwable {
                System.out.println("before..");
                Object proceed = invocation.proceed();
                System.out.println("after..");
                return proceed;
            }
        };
        return new DefaultPointcutAdvisor(pointcut, advice);
    }
}
